﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using FD.RemoteAssistant.Core.Containers;
using FD.RemoteAssistant.Core.Extensions;

namespace FD.RemoteAssistant.Core
{
    /*
     * CreatedOn: 2018-05-15
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    public class RuntimeContext
    {
        private RuntimeContext() { }

        public static RuntimeContext Current { get; } = new RuntimeContext();

        public List<IRemoteSetting> RemoteSettings { get; } = new List<IRemoteSetting>();

        public IContainer Container { get; private set; }

        public void Register(IContainer container)
        {
            Container = container;
        }

        public bool Exists(string server, string userName)
        {
            return RemoteSettings.Any(a => a.Server.IgnoreCaseEquals(server) && a.UserName.IgnoreCaseEquals(userName));
        }

        public IRemoteSetting FirstOrDefault(Func<IRemoteSetting, bool> condition = null)
        {
            if (condition == null)
            {
                return RemoteSettings.FirstOrDefault();
            }
            return RemoteSettings.FirstOrDefault(condition);
        }

        public bool AddSetting(IRemoteSetting remoteSetting, int index = -1)
        {
            if (RemoteSettings.Exists(rs => rs.Server == remoteSetting.Server && rs.UserName == remoteSetting.UserName))
            {
                return false;
            }
            if (index < 0 || index > RemoteSettings.Count - 1)
                RemoteSettings.Add(remoteSetting);
            else
            {
                RemoteSettings.Insert(index, remoteSetting);
            }
            return true;
        }

        public bool AddSettings(IList<IRemoteSetting> remoteSettings)
        {
            foreach (var item in remoteSettings)
            {
                AddSetting(item);
            }
            return true;
        }

        public int RemoveSetting(IRemoteSetting remoteSetting)
        {
            var index = RemoteSettings.IndexOf(remoteSetting); ;
            if (index != -1)
            {
                RemoteSettings.Remove(remoteSetting);
                return index;
            }

            return -1;
        }

        public bool RemoveSetting(Predicate<IRemoteSetting> condition = null)
        {
            if (condition == null)
                return RemoteSettings.RemoveAll(a => true) > 0;
            return RemoteSettings.RemoveAll(condition) > 0;
        }

        public IEnumerable<IRemoteSetting> GetRemoteSettings(Func<IRemoteSetting, bool> condition = null)
        {
            if (condition == null)
                return RemoteSettings;
            return RemoteSettings.Where(condition);
        }

        public bool RemoveAll()
        {
            RemoteSettings.Clear();
            return true;
        }
    }
}
